
package utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
/**
 * @author lishunlin110
 * @version 1.0
 * @description: 工具类
 * @date 2021/12/10 19:33
 */
public class RabbitMQUtils {

    private static ConnectionFactory factory;

    // 重量级资源，期望只在类加载时执行一次
    static {
        factory = new ConnectionFactory();
        // 设置接入点\用户名\密码，在配置信息部分
        factory.setHost("amqp-cn-7pp2h323i01m.mq-amqp.cn-shenzhen-429403-a.aliyuncs.com");
        factory.setUsername("MjphbXFwLWNuLTdwcDJoMzIzaTAxbTpMVEFJNXRRU01obVo5RG5NTGRTalhOQk4=");
        factory.setPassword("ODIyRUFGNkU3RUU0M0FGQjY2N0JDMTJGODQ3QkQ1M0FDQjNDNjU4MToxNjM5MTM2NTM4NDUy");
        // 设置为true，开启Connection自动恢复功能；设置为false，关闭Connection自动恢复功能
        factory.setAutomaticRecoveryEnabled(true);
        factory.setNetworkRecoveryInterval(5000);
        // 配置vhost和端口号，默认端口为非加密端口5672，加密端口5671
        factory.setVirtualHost("lsl");
        factory.setPort(5672);
        // 基于网络环境合理设置超时时间
        factory.setConnectionTimeout(30 * 1000);
        factory.setHandshakeTimeout(30 * 1000);
        factory.setShutdownTimeout(0);
    }

    // 定义提供连接对象的方法
    public static Connection getConnection() {
        try {
            return factory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    // 定义关闭通道和连接的方法
    public static void closeAll(Channel chan, Connection conn) {
        try{
            if(chan != null)  chan.close();
            if(conn != null)  conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}